<template>
  <div class="main-container">
    <!-- 页面标题和货品信息 -->
    <div class="page-header" v-if="currentGoodsInfo.goodsCode">
      <div class="goods-info">
        <h3>{{ currentGoodsInfo.goodsName }} {{ currentGoodsInfo.goodsCode }}</h3>
        <div class="goods-details">
          <span>货品类型：{{ currentGoodsInfo.goodsType || '饮品类' }}</span>
          <span>规格型号：{{ currentGoodsInfo.specs || '20*50*60' }}</span>
          <span>单位：{{ currentGoodsInfo.unit || '瓶' }}</span>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-if="stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.inboundQuantity || 0 }}</div>
            <div class="stat-label">入库数量</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.inboundAmount || '0.00' }}</div>
            <div class="stat-label">入库金额</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.outboundQuantity || 0 }}</div>
            <div class="stat-label">出库数量</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.outboundAmount || '0.00' }}</div>
            <div class="stat-label">出库金额</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="search-filter">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="出入库单号">
          <el-input v-model="searchForm.documentCode" placeholder="请输入出库单号/入库单号" clearable />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="searchForm.businessType" placeholder="请选择" clearable style="width: 150px">
            <el-option label="入库" value="入库" />
            <el-option label="出库" value="出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="出入库类型">
          <el-select v-model="searchForm.flowType" placeholder="请选择" clearable style="width: 150px">
            <el-option label="进货入库" value="进货入库" />
            <el-option label="销售出库" value="销售出库" />
            <el-option label="调拨入库" value="调拨入库" />
            <el-option label="调拨出库" value="调拨出库" />
            <el-option label="退货入库" value="退货入库" />
            <el-option label="退货出库" value="退货出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="出入库日期">
          <el-date-picker
            v-model="searchForm.operationDate"
            type="date"
            placeholder="请选择"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="制单日期">
          <el-date-picker
            v-model="searchForm.createDate"
            type="date"
            placeholder="请选择"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <div class="table-container">
      <el-table :data="tableData" :loading="loading" border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">{{ (pagination.page - 1) * pagination.pageSize + $index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="documentCode" label="出入库单号" width="140" />
        <el-table-column prop="operationDate" label="出入库日期" width="120" />
        <el-table-column prop="businessType" label="业务类型" width="100" />
        <el-table-column prop="flowType" label="出入库类型" width="120" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="inboundQuantity" label="入库数量" width="100">
          <template #default="{ row }">
            <span v-if="row.businessType === '入库'">{{ row.inboundQuantity || row.quantity || 0 }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="outboundQuantity" label="出库数量" width="100">
          <template #default="{ row }">
            <span v-if="row.businessType === '出库'">{{ row.outboundQuantity || row.quantity || 0 }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="inboundAmount" label="入库金额" width="100">
          <template #default="{ row }">
            <span v-if="row.businessType === '入库'">{{ row.inboundAmount || row.amount || '0.00' }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="outboundAmount" label="出库金额" width="100">
          <template #default="{ row }">
            <span v-if="row.businessType === '出库'">{{ row.outboundAmount || row.amount || '0.00' }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="经办人" width="100" />
        <el-table-column prop="creator" label="制单人" width="100" />
        <el-table-column prop="department" label="所在部门" width="120" />
        <el-table-column prop="createTime" label="制单时间" width="160" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  
</template>

<script lang="ts" setup name="kcLs">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useInventoryQueryApi } from '/@/api/inventory/inventoryQuery'

const route = useRoute()
const api = useInventoryQueryApi()

const loading = ref(false)
const tableData = ref<any[]>([])

// 当前货品信息
const currentGoodsInfo = reactive({
  goodsCode: '',
  goodsName: '',
  goodsType: '',
  specs: '',
  unit: '',
  warehouseName: ''
})

// 统计数据
const stats = ref<any>(null)

const searchForm = reactive({
  documentCode: '', // 出入库单号
  businessType: '', // 业务类型：入库/出库
  flowType: '', // 出入库类型
  operationDate: null, // 出入库日期
  createDate: null, // 制单日期
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})

// 移除仓库选项加载，默认查询全部仓库

const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      documentCode: searchForm.documentCode || undefined,
      goodsCode: currentGoodsInfo.goodsCode || undefined, // 使用传入的货品编号
      businessType: searchForm.businessType || undefined,
      flowType: searchForm.flowType || undefined,
      operationDate: searchForm.operationDate || undefined,
      createDate: searchForm.createDate || undefined,
      page: pagination.page,
      pageSize: pagination.pageSize,
    }
    
    const res = await api.getStockFlow(params)
    if (res.data && res.data.result) {
      tableData.value = res.data.result.items || []
      pagination.total = res.data.result.total || 0
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (e) {
    ElMessage.error('加载流水数据失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const res = await api.getStats({
      goodsCode: currentGoodsInfo.goodsCode, // 使用传入的货品编号
      warehouseName: undefined // 不传仓库名称，查询全部仓库
    })
    if (res.data && res.data.result) {
      stats.value = res.data.result
    }
  } catch (e) {
    console.error('加载统计数据失败:', e)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
  loadStats()
}

const handleReset = () => {
  searchForm.documentCode = ''
  searchForm.businessType = ''
  searchForm.flowType = ''
  searchForm.operationDate = null
  searchForm.createDate = null
  pagination.page = 1
  loadData()
  loadStats()
}

const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      goodsCode: currentGoodsInfo.goodsCode, // 使用传入的货品编号
      page: 1,
      pageSize: 10000 // 导出所有数据
    }
    const res = await api.exportStockFlow(params)
    
    // 创建下载链接
    const blob = new Blob([res.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `出入库流水_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const handleRefresh = () => {
  loadData()
  loadStats()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  loadData()
}

onMounted(async () => {
  // 处理路由参数
  if (route.query.goodsCode) {
    currentGoodsInfo.goodsCode = route.query.goodsCode as string
  }
  if (route.query.goodsName) {
    currentGoodsInfo.goodsName = route.query.goodsName as string
  }
  if (route.query.warehouseName) {
    currentGoodsInfo.warehouseName = route.query.warehouseName as string
  }
  
  await loadData()
  await loadStats()
})
</script>

<style scoped>
.main-container { 
  padding: 20px; 
}

.page-header {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.goods-info h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.goods-details {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.blue {
  color: #409eff;
}

.stat-value.orange {
  color: #e6a23c;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.search-filter {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form { 
  margin: 0; 
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container { 
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination { 
  display: flex; 
  justify-content: flex-end; 
  padding: 12px 0; 
}
</style>




